<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
                    v-hasFunc="'sys:releaselog:del'">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="plus" @click="handleAdd"
                    v-hasFunc="'sys:releaselog:add'">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate"
                    v-hasFunc="'sys:releaselog:put'">修改</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" ref="tableRef" :data="dataList" @selection-change="handleSelectionChange"
            highlight-current-row @row-click="handleRowClick">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="版本号" align="center" prop="versionCode" :show-overflow-tooltip="true"
                v-if="columns.showColumn('versionCode')">
                <template #default="{ row }">
                    {{ row.versionCode + (row.versionName || "") }}
                </template>
            </el-table-column>
            <el-table-column label="更新明细" align="center" prop="summary" :show-overflow-tooltip="true"
                v-if="columns.showColumn('summary')">
                <template #default="scope">
                    {{ scope.row.summary }}
                </template>
            </el-table-column>
            <el-table-column label="发布日期" align="center" prop="releaseDate" :show-overflow-tooltip="true"
                v-if="columns.showColumn('releaseDate')">
                <template #default="{ row }">
                    {{ parseTime(row.releaseDate, 'YYYY-MM-DD') }}
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true"
                v-if="columns.showColumn('status')">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'primary'" :disable-transitions="false">
                        {{ scope.row.status === 1 ? '已发布' : '暂存' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="{ row }">
                    <el-button type="primary" v-hasFunc="'sys:releaselog:release'" v-if="row.status === 0" text
                        icon="position" @click="handleRowRelease(row)">发布</el-button>
                    <el-button type="primary" text icon="edit" v-hasFunc="'sys:releaselog:put'" v-if="row.status === 0"
                        @click="handleUpdate(row)">编辑</el-button>
                    <el-button type="primary" v-if="row.status === 1" text icon="view"
                        @click="handleView(row)">查看</el-button>
                    <el-button type="primary" v-if="row.status === 1" text @click="handleRevoke(row)"
                        v-hasFunc="'sys:releaselog:revoke'">撤销</el-button>
                    <el-button type="danger" text icon="delete" @click="handleDelete(row)"
                        v-hasFunc="'sys:releaselog:del'">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" v-model="open" width="60%" append-to-body align-center destroy-on-close draggable
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :lg="24">
                        <el-form-item label="版本号" prop="versionCode">
                            <el-input v-model="form.versionCode" placeholder="请输入版本号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="版本名称" prop="versionName">
                            <el-input v-model="form.versionName" placeholder="请输入版本名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                        <el-form-item label="更新明细" prop="summary">
                            <el-row :gutter="20" style="width: 100%;">
                                <el-col :span="12">
                                    <Codemirror v-model="form.summary" :extensions="[markdown(), oneDark]"
                                        placeholder="请输入更新明细" style="height: 450px;" />
                                </el-col>
                                <el-col :span="12">
                                    <div v-html="markdownHtml"></div>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="handleStaged">暂 存</el-button>
                <el-button type="primary" @click="handleRelease" v-if="operateType == 0 || operateType == 1">发
                    布</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { listReleaseLog, getReleaseLog, delReleaseLog, stage, release, revoke } from "@/api/system/releaselog.js";
import { Codemirror } from "vue-codemirror";
import { oneDark } from "@codemirror/theme-one-dark";
import { markdown } from "@codemirror/lang-markdown"
import { marked } from "marked";

const { proxy } = getCurrentInstance()


//弹窗操作类型
//0:新增，1：修改，2:查看
const operateType = ref(0)
//表单ref
const formRef = ref();
const tableRef = ref();
// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);

const markdownHtml = computed(() => {
    return marked.parse(form.value?.summary || '')
})

// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    sort: 'CreatedAt',
    sortType: 'desc',
});



const state = reactive({
    single: true,
    multiple: true,
    form: {

    },
    rules: {
        versionCode: [
            { required: true, message: '版本号不能为空', trigger: 'blur' },
            { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式必须为x.x.x，如:1.0.0', trigger: 'blur' }
        ]
    },
    options: {
    }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
    { visible: true, prop: 'versionCode', label: '版本号' },
    { visible: true, prop: 'summary', label: '更新明细' },
    { visible: true, prop: 'releaseDate', label: '发布日期' },
    { visible: true, prop: 'status', label: '状态' },
]);

// 获取列表方法
const getList = () => {
    loading.value = true;
    listReleaseLog(queryParams).then((response) => {
        dataList.value = response.result;
        total.value = response.totalNum;
        loading.value = false;
    });
};

// 重置表单
const reset = () => {
    form.value = {
        id: undefined,
        versionCode: undefined,
        versionName: undefined,
        summary: undefined,
        relatedUrl: undefined,
        status: undefined,
        releaseDate: undefined,
    };
    proxy.resetForm("form");
};

// 搜索按钮操作
const handleQuery = () => {
    queryParams.pageIndex = 1;
    getList();
};

// 重置按钮操作
const resetQuery = () => {
    reset();
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    selected.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
    reset();
    operateType.value = 0;
    open.value = true;
    title.value = "新增版本";
};

// 修改按钮操作
const handleUpdate = (row) => {
    reset();
    operateType.value = 1;
    const key = row.id || selected.value;
    getReleaseLog(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "修改版本";
    });
};


//查看
const handleView = (row) => {
    reset();
    operateType.value = 2;
    var key = row.id;
    getReleaseLog(key).then((response) => {
        Object.assign(form.value, response);
        open.value = true;
        title.value = "查看明细";
    });
}


//暂存
const handleStaged = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                form.value.status = 0; // 0表示暂存状态
                stage(form.value).then(() => {
                    proxy.$modal.msgSuccess("暂存成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
}

const handleRowRelease = (row) => {
    proxy.$modal.confirm("确定要发布版本说明吗？")
        .then(() => {
            return release(row);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("发布成功");
        })
        .catch(() => { });
}

//发布
const handleRelease = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm((valid) => {
            if (valid) {
                form.value.status = 1; // 1表示发布状态
                release(form.value).then(() => {
                    proxy.$modal.msgSuccess("发布成功");
                    open.value = false;
                    getList();
                });
            }
        });
    }
}

// 撤销发布
const handleRevoke = (row) => {
    proxy.$modal.confirm("确定要撤销已发布的版本吗？此操作将把状态改回暂存。")
        .then(() => {
            return revoke(row.id);
        })
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("撤销发布成功");
        })
        .catch(() => { });
};


// 删除按钮操作
const handleDelete = (row) => {
    const keys = [].concat(row.id || selected.value);
    proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
        .then(() => delReleaseLog(keys))
        .then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
};

// 行点击事件
const handleRowClick = (row) => {
    tableRef.value.toggleRowSelection(row);
};
// 页面加载时调用获取列表方法
onMounted(getList);
</script>
